<template>
  <Dialog v-model="dialogVisible" title="检验类型导入" width="400">
    <el-upload
      ref="uploadRef"
      v-model:file-list="fileList"
      :action="importUrl + '?updateSupport=' + updateSupport"
      :auto-upload="false"
      :disabled="formLoading"
      :headers="uploadHeaders"
      :limit="1"
      :on-error="submitFormError"
      :on-exceed="handleExceed"
      :on-success="submitFormSuccess"
      :on-change="handleChange"
      accept=".xlsx, .xls"
      drag
    >
      <Icon icon="ep:upload" />
      <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
      <template #tip>
        <div class="el-upload__tip text-center">
<!--          <div class="el-upload__tip">-->
<!--            <el-checkbox v-model="updateSupport" />-->
<!--            是否更新已经存在的用户数据-->
<!--          </div>-->
          <span>仅允许导入 xls、xlsx 格式文件。</span>
          <el-link
            :underline="false"
            style="font-size: 12px; vertical-align: baseline"
            type="primary"
            @click="importTemplate"
          >
            下载模板1 检验类型
          </el-link>
          <br/>
          <span>仅允许导入 xls、xlsx 格式文件。</span>
          <el-link
            :underline="false"
            style="font-size: 12px; vertical-align: baseline"
            type="primary"
            @click="importTemplate2"
          >
            下载模板2 检验项目
          </el-link>
        </div>
      </template>
    </el-upload>
    <template #footer>
      <el-button :disabled="formLoading" type="primary" @click="submitForm">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script lang="ts" setup>
import { getAccessToken, getTenantId } from '@/utils/auth'
import download from '@/utils/download'
import { InspectionTypeApi, InspectionTypeVO } from '@/api/opticore/inspection/type'
import { InspectionItemApi, InspectionItemVO } from '@/api/opticore/inspection/item'
import { ElMessage } from 'element-plus'

defineOptions({ name: 'SystemUserImportForm' })

const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const formLoading = ref(false) // 表单的加载中
const uploadRef = ref()
const importUrlType =
  import.meta.env.VITE_BASE_URL + import.meta.env.VITE_API_URL + '/opticore/inspection-type/import'
const importUrlItem =
  import.meta.env.VITE_BASE_URL + import.meta.env.VITE_API_URL + '/opticore/inspection-item/import'
const importUrl = ref(importUrlType) // 默认类型导入
const uploadHeaders = ref() // 上传 Header 头
const fileList = ref([]) // 文件列表
const updateSupport = ref(0) // 是否更新已经存在的用户数据

/** 打开弹窗 */
const open = () => {
  dialogVisible.value = true
  updateSupport.value = 0
  fileList.value = []
  resetForm()
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const submitForm = async () => {
  if (fileList.value.length == 0) {
    message.error('请上传文件')
    return
  }
  // 提交请求
  uploadHeaders.value = {
    Authorization: 'Bearer ' + getAccessToken(),
    'tenant-id': getTenantId()
  }
  formLoading.value = true
  uploadRef.value!.submit()
}

/** 文件上传成功 */
const emit = defineEmits(['update:modelValue', 'success'])
const submitFormSuccess = (response: any) => {
  if (response.code !== 0) {
    let msg = response.msg
    if (msg && msg.includes('\n')) {
      msg = msg.split('\n').join('<br/>')
    }
    ElMessage({ message: msg, type: 'error', dangerouslyUseHTMLString: true })
    formLoading.value = false
    dialogVisible.value = false
    return
  }
  // 优化：根据返回的data数组长度显示导入成功条数
  let count = Array.isArray(response.data) ? response.data.length : 0
  let text = `导入成功数量：${count}条`;
  ElMessage.success(text)
  emit('success')
  dialogVisible.value = false
}

/** 上传错误提示 */
const submitFormError = (): void => {
  message.error('上传失败，请您重新上传！')
  formLoading.value = false
}

/** 重置表单 */
const resetForm = async (): Promise<void> => {
  // 重置上传状态和文件
  formLoading.value = false
  await nextTick()
  uploadRef.value?.clearFiles()
}

/** 文件数超出提示 */
const handleExceed = (): void => {
  message.error('最多只能上传一个文件！')
}

/** 下载模板操作 */
const importTemplate = async () => {
  const res = await InspectionTypeApi.importInspectionTemplate()
  download.excel(res, '检验类型导入模版.xls')
}

const importTemplate2 = async () => {
  const res = await InspectionItemApi.importInspectionTemplate()
  download.excel(res, '检验项目导入模版.xls')
}



const importDialogVisible = ref(false)
const handleImport = () => {
  importDialogVisible.value = true
}
const handleImportSuccess = () => {
  importDialogVisible.value = false
  getList()
}

defineProps({
  modelValue: Boolean
})

const handleChange = (file, fileList) => {
  // 你可以根据文件名自定义判断规则
  if (file.name.includes('项目')) {
    importUrl.value = importUrlItem
  } else {
    importUrl.value = importUrlType
  }
  // 这里可以根据需要做更多判断
}
</script>
